const {
	Service
} = require('uni-cloud-router');
const {
	eachDocs,
	markets,
	setLineItem
} = require("lg-utils-db");
const {
	parser,
	success,
	exception,
	error,
	typeOf,
	Clock,
	getTimingLogger,
	StatusEnum
} = require("lg-utils");
const {
	confMap,
	kLineMap
} = require("lg-constant");
const {
	getStockBaseInfoList,
	getStockHQNodeData,
	getStockCount,
	getStockDWMKLine
} = require("lg-request-stock")

const db = uniCloud.database();
const dbCmd = db.command
const stockColl = db.collection("stock-base");
const stockDayLineColl = db.collection("stock-day-line");
const stockWeekLineColl = db.collection("stock-week-line");
const stockMonthLineColl = db.collection("stock-month-line");
const logTimingColl = db.collection("log-timing");
module.exports = class TimingService extends Service {
	async updateDayLine() {
		logTimingColl.add(getTimingLogger({
			info: "updateDayLine >>> start >>>>"
		}))
		try {
			const marketsInfo = await markets() || {};
			const {
				SH,
				SZ
			} = marketsInfo;
			if (SH && SZ && SZ !== "close" && SH !== "close") {

				const {
					status,
					errorList,
					error,
					count
				} = await eachDocs(async ({
					symbol
				} = {}) => {
					return await setLineItem({
						type: "day",
						symbol
					});
				}, {
					coll: stockDayLineColl,
					fields: {
						name: true,
						symbol: true,
						code: true
					},
					pageSize: 100
				}) || {};

				if (status) {
					logTimingColl.add(getTimingLogger({
						action: "updateDayLine",
						info: `count:${count},errorList:${errorList}`,
					}))
				} else {
					logTimingColl.add(getTimingLogger({
						action: "updateDayLine",
						info: error,
						type: confMap.get("timing-error"),
					}))
				}

			} else {
				logTimingColl.add(getTimingLogger({
					action: "updateDayLine",
					info: marketsInfo,
					type: confMap.get("timing-common")
				}))
			}
		} catch (e) {
			logTimingColl.add(getTimingLogger({
				action: "updateDayLine",
				info: e,
				type: confMap.get("timing-exception")
			}))
		}

		logTimingColl.add(getTimingLogger({
			info: "updateDayLine >>> end >>>>"
		}))

	}
	async ping() {
		try {
		    console.log(StatusEnum.SUCCESS);
		} catch (e) {
			throw e
		}
	}

	async removeLogTimingListAll() {
		try {
			return await logTimingColl.where({
				_id: dbCmd.exists(true)
			}).remove();

		} catch (e) {
			throw e
		}
	}
	
	

}
